package com.gzceb.zhgjj.security.dao;

// default package

import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.hibernate.LockMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.gzceb.zhgjj.security.entity.SysAuthoritiesResources;
import com.gzceb.zhgjj.security.entity.SysResources;

import com.gzceb.zhgjj.security.dao.SysResourcesDAO;
import com.gzceb.zhgjj.security.dao.SysRolesAuthoritiesDAO;
import com.gzceb.zhgjj.security.dao.SysAuthoritiesResourcesDAO;

import com.gzceb.zhgjj.security.entity.SysAuthorities;
import com.gzceb.zhgjj.util.Utils;

/**
 * A data access object (DAO) providing persistence and search support for
 * SysAuthorities entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see .SysAuthorities
 * @author MyEclipse Persistence Tools
 */

public class SysAuthoritiesDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory
			.getLogger(SysAuthoritiesDAO.class);
	// property constants
	public static final String AUTHORITY_NAME = "authorityName";
	public static final String AUTHORITY_DESC = "authorityDesc";
	public static final String ENABLED = "enabled";
	public static final String ISSYS = "issys";
	public static final String MODULE = "module";

	// 资源dao
	private SysResourcesDAO sysResourcesDao;

	// 角色和权限的对应关系的dao
	private SysRolesAuthoritiesDAO sysRolesAuthoritiesDao;

	// 权限和资源对应关系的dao
	private SysAuthoritiesResourcesDAO sysAuthoritiesResourcesDao;

	protected void initDao() {
		// do nothing
	}

	/*
	 * 将从页面返回的权限对象进行保存。
	 */
	public void persist(SysAuthorities transientInstance) {

		log.debug("权限 " + transientInstance.getAuthorityDesc() + " 持久化!");

		try {

			// 为写入的权限设置唯一id
			transientInstance.setAuthorityId(Utils.getPkId() + "");

			String authorityName = transientInstance.getAuthorityName();

			// 当权限标识前缀不为"AUTH_"时，要添加该标识。
			if (authorityName.startsWith("AUTH")) {

				if (!authorityName.startsWith("AUTH_")) {
					authorityName = authorityName.substring(0, 4) + "_"
							+ authorityName.substring(4);
					transientInstance.setAuthorityName(authorityName);
				}

			} else {
				transientInstance.setAuthorityName("AUTH_" + authorityName);
			}

			// 持久化
			getHibernateTemplate().persist(transientInstance);

			log.debug("权限 " + transientInstance.getAuthorityDesc() + " 持久化成功！");

		} catch (RuntimeException re) {

			log.error("权限 " + transientInstance.getAuthorityDesc() + " 持久化失败！",
					re);
			throw re;

		}
	}

	/**
	 * 根据平台中的子系统返回权限列表。
	 * 
	 * @author
	 * @return
	 */
	public List<SysAuthorities> findAuthoritiesLst(String xtmk) {
		try {
			List<SysAuthorities> results = getHibernateTemplate().find(
					"from SysAuthorities where module='" + xtmk + "'");

			return results;

		} catch (RuntimeException re) {

			throw re;
		}
	}

	/**
	 * 根据权限id，得到以资源id为键，"true"为值的Map。
	 * 
	 * @author
	 * @param authorityId
	 * @return
	 */
	public HashMap getSelectedResourcesMap(String authorityId) {
		try {

			List<String> results = getSession()
					.createSQLQuery(
							"select a.resource_id "
									+ "from sys_resources a, sys_authorities_resources b "
									+ "where a.resource_id = b.resource_id and b.Authority_id='"
									+ authorityId + "' and a.enabled=1").list();

			HashMap<String, String> hashMap = new HashMap<String, String>(0);

			for (String resourcesId : results) {
				hashMap.put(resourcesId, "true");
			}

			return hashMap;
		} catch (RuntimeException re) {

			throw re;
		}
	}

	/*
	 * 保存权限和资源之间一对多的关系。
	 */
	public boolean saveAuthorityAndReSource(String authorityId,
			String[] resourceskey) {

		SysAuthorities sysAuthorities = findById(authorityId);
		SysResources sysResources = null;
		SysAuthoritiesResources sysAuthoritiesResources;

		// 在重新设置之前先删除之前所拥有的全部对应关系
		sysAuthoritiesResourcesDao
				.deleteOldAuthorityAndResourceRelative(authorityId);

		try {
			/*
			 * 将用户在前台通过checkbox选中的所有权限id提取出来。 在进行保存之前，首先要通过id提取该权限的实例，
			 * 为角色权限关联表sysRolesAuthorities的setSysAuthorities()提供数据。
			 * 最后通过hibernate的save()方法保存新建的sysRolesAuthorities实例。
			 */
			for (String resId : resourceskey) {

				sysResources = sysResourcesDao.findById(resId);

				/*
				 * 生成一个新的实例很重要，否则会报 identifier of an instance of xxx was altered
				 * from xxx to xxx"的异常。
				 */
				sysAuthoritiesResources = new SysAuthoritiesResources();
				sysAuthoritiesResources.setId(Utils.getPkId());
				sysAuthoritiesResources.setSysResources(sysResources);
				sysAuthoritiesResources.setSysAuthorities(sysAuthorities);
				sysAuthoritiesResources.setEnabled(true);

				getHibernateTemplate().save(sysAuthoritiesResources);

			}

		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}

		return true;
	}

	/**
	 * 根据权限id删除该权限，角色和权限，权限和资源的关系。
	 * 
	 * @author
	 * @param authorityId
	 */
	public void delete(String authorityId) {
		log.debug("根据权限id删除该权限！权限id为 ： " + authorityId);
		try {

			SysAuthorities authority = findById(authorityId);

			getHibernateTemplate().delete(authority);

			log.debug("权限id" + authorityId + "删除成功！");
		} catch (RuntimeException re) {
			log.error("权限id" + authorityId + "删除失败！", re);
			throw re;
		}
	}

	public void save(SysAuthorities transientInstance) {
		log.debug("saving SysAuthorities instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(SysAuthorities persistentInstance) {
		log.debug("deleting SysAuthorities instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public SysAuthorities findById(java.lang.String id) {
		log.debug("getting SysAuthorities instance with id: " + id);
		try {
			SysAuthorities instance = (SysAuthorities) getHibernateTemplate()
					.get("SysAuthorities", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(SysAuthorities instance) {
		log.debug("finding SysAuthorities instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding SysAuthorities instance with property: "
				+ propertyName + ", value: " + value);
		try {
			String queryString = "from SysAuthorities as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByAuthorityName(Object authorityName) {
		return findByProperty(AUTHORITY_NAME, authorityName);
	}

	public List findByAuthorityDesc(Object authorityDesc) {
		return findByProperty(AUTHORITY_DESC, authorityDesc);
	}

	public List findByEnabled(Object enabled) {
		return findByProperty(ENABLED, enabled);
	}

	public List findByIssys(Object issys) {
		return findByProperty(ISSYS, issys);
	}

	public List findByModule(Object module) {
		return findByProperty(MODULE, module);
	}

	public List findAll() {
		log.debug("finding all SysAuthorities instances");
		try {
			String queryString = "from SysAuthorities";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public SysAuthorities merge(SysAuthorities detachedInstance) {
		log.debug("merging SysAuthorities instance");
		try {
			SysAuthorities result = (SysAuthorities) getHibernateTemplate()
					.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(SysAuthorities instance) {
		log.debug("attaching dirty SysAuthorities instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(SysAuthorities instance) {
		log.debug("attaching clean SysAuthorities instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public SysResourcesDAO getSysResourcesDAO() {
		return this.sysResourcesDao;
	}

	public void setSysResourcesDAO(SysResourcesDAO sysResourcesDao) {
		this.sysResourcesDao = sysResourcesDao;
	}

	public SysRolesAuthoritiesDAO getSysRolesAuthoritiesDAO() {
		return this.sysRolesAuthoritiesDao;
	}

	public void setSysRolesAuthoritiesDAO(
			SysRolesAuthoritiesDAO sysRolesAuthoritiesDao) {
		this.sysRolesAuthoritiesDao = sysRolesAuthoritiesDao;
	}

	public SysAuthoritiesResourcesDAO getSysAuthoritiesResourcesDAO() {
		return sysAuthoritiesResourcesDao;
	}

	public void setSysAuthoritiesResourcesDAO(
			SysAuthoritiesResourcesDAO sysAuthoritiesResourcesDao) {
		this.sysAuthoritiesResourcesDao = sysAuthoritiesResourcesDao;
	}

	public static SysAuthoritiesDAO getFromApplicationContext(
			ApplicationContext ctx) {
		return (SysAuthoritiesDAO) ctx.getBean("SysAuthoritiesDAO");
	}
}